package cn.qh.seasonal.controller;

import cn.qh.seasonal.entity.Factory;
import cn.qh.seasonal.exception.ExceptionCodeConfiguration;
import cn.qh.seasonal.exception.HttpException;
import cn.qh.seasonal.exception.NotFoundException;
import cn.qh.seasonal.service.FactoryService;
import cn.qh.seasonal.vo.CommonResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.qh.seasonal.entity.Shift;
import cn.qh.seasonal.dto.ShiftDTO;
import cn.qh.seasonal.service.ShiftService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;

/**
 * 控制层
 * 控制层
 **/
@RestController
@RequestMapping("shift")
@Api
public class ShiftController {
    /**
     * 服务对象
     */
    @Resource
    private ShiftService shiftService;

    @Resource
    private FactoryService factoryService;

    /**
     * 分页查询所有数据
     *
     * @param current 分页对象
     * @return 所有数据
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询所有数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = CommonResponse.class)
    @ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int")
    @CrossOrigin
    public Page<Shift> selectAll(@RequestParam(defaultValue = "1") int current) {
        Page page = new Page();
        page.setCurrent(current);
        page.setSize(3);
        this.shiftService.page(page);
        return page;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @CrossOrigin
    @ApiOperation(value = "通过主键查询单条数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = CommonResponse.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    public Shift selectOne(@PathVariable Serializable id) {
        return this.shiftService.getById(id);
    }

    /**
     * 新增数据
     *
     * @param shiftDTO 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation(value = "新增", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = CommonResponse.class)
    @CrossOrigin
    public boolean insert(@RequestBody ShiftDTO shiftDTO) throws ParseException {
        Shift shift = new Shift();
        BeanUtils.copyProperties(shiftDTO, shift);
        //用户输入的开始时间
        String startTime = shift.getStartTime();
        //用户输入的结束时间
        String endTime = shift.getEndTime();
        //拼接开始时间
        String start = "2021-11-10 " + startTime;
        //拼接结束时间
        String end = "2021-11-10 " + endTime;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm");
        //用户输入跨天
        String kua = "2021-11-11 " + endTime;
        //用户输入跨天时间 拼接转成date
        Date kuatian = sdf.parse(kua);
        //用户输入的开始时间 拼接转成date
        Date parse = sdf.parse(start);
        System.out.println("开始时间" + parse);
        //用户输入的结束时间 拼接转成date
        Date parse2 = sdf.parse(end);
        System.out.println("结束时间" + parse2);
        //通过时令 和 工厂 查出来班次有几个 在进行判断
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("seasonalId", shift.getSeasonalId());
        queryWrapper.eq("shiftGcId", shift.getShiftGcId());
        List<Shift> list = shiftService.list(queryWrapper);
        System.out.println(list.toString());
        //这是跨天了
        QueryWrapper queryWrapper33 = new QueryWrapper();
        queryWrapper33.eq("seasonalId", shift.getSeasonalId());
        queryWrapper33.eq("shiftGcId", shift.getShiftGcId());
//        queryWrapper33.eq("isCross", 1);
        List<Shift> list22 = shiftService.list(queryWrapper33);

        QueryWrapper ww = new QueryWrapper();
        ww.eq("shiftGcId", shift.getShiftGcId());
        ww.eq("shiftName", shift.getShiftName());
        ww.eq("seasonalId", shift.getSeasonalId().toString());




//YOUGE1 BUG BUG BUG !!!
//        for (Shift shift5 : list) {
            QueryWrapper queryWrapper44 = new QueryWrapper();
            queryWrapper44.eq( "isCross",1);
            int couunt22  = shiftService.count(queryWrapper44);
            System.out.println("数据库有几个" + couunt22);

            int count = shiftService.count(ww);
            if (count != 0) {
                System.out.println("新增失败！");
//            throw new NotFoundException(1004);
                //这个回头删掉，返回throw
                return false;
            } else {
                System.out.println("进入方法");
                //判断有没有选跨自然日
                if (shift.getIsCross() == 0) {
                    //判断用户输入的时间 是否小于 结束时间
                    if (!parse.after(parse2)) {
                        //判断用户输入的时间是否小于数据里的时间
                        //循环拿到数据库里得时间
                        for (Shift shift1 : list) {
                            //数据库结束时间拿出来转date
                            Date pjendTime = sdf.parse("2021-11-10 " + shift1.getEndTime());
                            System.out.println(shift1.getStartTime());
                            //数据库开始时间拿出来转date
                            Date pjstartTime = sdf.parse("2021-11-10 " + shift1.getStartTime());
                            System.out.println(shift1.getEndTime());
                            //判断 开始时间是否大于数据库的结束时间
                            //开始时间
                            Date leftStartDate = parse;
                            //结束时间
                            Date leftEndDate = parse2;
                            //比较时间段
                            Date rightStartDate = pjstartTime;
                            Date rightEndDate = pjendTime;
                            //判断    |__________|
                            //判断    |__________|
                            if (leftStartDate.getTime() < rightEndDate.getTime() && leftEndDate.getTime() < rightStartDate.getTime()) {
                                System.out.println("两段时间存在交集111111");
                                return false;
                            }

                            if (((leftStartDate.getTime() >= rightStartDate.getTime())
                                    && leftStartDate.getTime() < rightEndDate.getTime())

                                    || ((leftStartDate.getTime() > rightStartDate.getTime())
                                    && leftStartDate.getTime() <= rightEndDate.getTime())

                                    || ((rightStartDate.getTime() >= leftStartDate.getTime())
                                    && rightStartDate.getTime() < leftEndDate.getTime())

                                    || ((rightStartDate.getTime() > leftStartDate.getTime())
                                    && rightStartDate.getTime() <= leftEndDate.getTime())) {
                                System.out.println("两段时间存在交集");
                                return false;
                            }
                        }
                    } else {
                        //没有小于
                        System.out.println("第一个时间大于第二个不能增加！！！");
                        return false;
                    }
                } else {
                    if (couunt22 <= 0) {
                        //跨自然日了！！！
                        System.out.println("跨自然日了！！！！");
                        //判断输入时间是否在结束时间之前
                        if (!parse.after(kuatian)) {
                            for (Shift shift1 : list22) {
                                //数据库结束时间拿出来转date
                                Date pjendTime = sdf.parse("2021-11-10 " + shift1.getEndTime());
                                //数据库开始时间拿出来转date
                                //这个地方有点小bug
                                Date pjstartTime = sdf.parse("2021-11-11 " + shift1.getStartTime());

                                //判断 开始时间是否大于数据库的结束时间
                                //开始时间
                                Date leftStartDate = parse;
                                //结束时间
                                Date leftEndDate = kuatian;
                                //比较时间段
                                Date rightStartDate = pjstartTime;
                                Date rightEndDate = pjendTime;
                                //判断    |__________|
                                if (leftStartDate.getTime() < rightEndDate.getTime() && leftEndDate.getTime() < rightStartDate.getTime()) {
                                    System.out.println("两段时间存在交集111111");
                                    return false;
                                }

                                if (((leftStartDate.getTime() >= rightStartDate.getTime())
                                        && leftStartDate.getTime() < rightEndDate.getTime())

                                        || ((leftStartDate.getTime() > rightStartDate.getTime())
                                        && leftStartDate.getTime() <= rightEndDate.getTime())

                                        || ((rightStartDate.getTime() >= leftStartDate.getTime())
                                        && rightStartDate.getTime() < leftEndDate.getTime())

                                        || ((rightStartDate.getTime() > leftStartDate.getTime())
                                        && rightStartDate.getTime() <= leftEndDate.getTime())) {
                                    System.out.println("两段时间存在交集22222222");
                                    return false;
                                }
                            }
                        } else {
                            //没有小于
                            System.out.println("第一个时间大于第二个不能增加！！！");
                            return false;
                        }
                    } else {
                        //没有小于
                        System.out.println("数据库一个季节 一个时令只能有一条跨天！！！");
                        return false;
                    }
                }
            }
//        }

        return this.shiftService.save(shift);
    }

    /**
     * 修改数据
     *
     * @param shiftDTO 实体对象
     * @return 修改结果
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改信息", produces = "application/json;charset=utf-8",
            httpMethod = "PUT", response = CommonResponse.class)
    @CrossOrigin
    public boolean update(@RequestBody ShiftDTO shiftDTO) {
        Shift shift = new Shift();
        BeanUtils.copyProperties(shiftDTO, shift);
        return this.shiftService.updateById(shift);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据主键删除信息", produces = "application/json;charset=utf-8",
            httpMethod = "DELETE", response = CommonResponse.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    @CrossOrigin
    public boolean delete(@PathVariable Serializable id) {
        return this.shiftService.removeById(id);
    }


    @GetMapping("/All")
    @ApiOperation(value = "分页查询所有数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = CommonResponse.class)
    @CrossOrigin
    public List<Shift> all(@RequestParam(name = "shiftGcId", required = false, defaultValue = "0") int shiftGcId, @RequestParam(name = "seasonalId", defaultValue = "0", required = false) int seasonalId) {
        List<Shift> shifts = shiftService.selectAllShift(shiftGcId, seasonalId);
        QueryWrapper<Shift> queryWrapper = new QueryWrapper();
        System.out.println("工厂传过来的工厂id" + shiftGcId);
        //通过传过来的id查找 工场对象
        queryWrapper.eq("shiftGcId", shiftGcId);
        List<Shift> list = shiftService.list(queryWrapper);
        System.out.println("这是第一个list结果：" + list);
        //第一次 找上面的
        if (list == null || list.size() == 0) {
            //拿到父id getParentId
            Factory byId = factoryService.getById(shiftGcId);
            System.out.println("班次没有 找父id第一次！！！" + byId.getParentId());
            List<Shift> shifts1 = shiftService.selectAllShift(byId.getParentId(), seasonalId);
            System.out.println("取到第一个父id返回集合！！！" + shifts1);
            if (shifts1.size() != 0) {
                return shifts1;
            } else {
                List<Shift> shifts2 = shiftService.selectAllShift(byId.getParentId(), seasonalId);
                if (shifts2.size() != 0) {
                    return shifts2;
                } else {
                    //第二个父id
                    Factory byId2 = factoryService.getById(byId.getParentId());
                    List<Shift> shifts3 = shiftService.selectAllShift(byId2.getParentId(), seasonalId);
                    if (shifts3 != null || shifts3.size() != 0) {
                        return shifts3;
                    }
                }
            }
        }
        return shifts;
    }
}
